package com.untrance.shop.common.utils;

import java.util.List;

import javax.persistence.Query;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

/**
 * @author eugene zadyra
 */
public class JpaUtils {
	
	private static Logger log = LoggerFactory.getLogger(JpaUtils.class);
	
	@SuppressWarnings("unchecked")
	public static <T> T getSingleResult(Query query) {
		List<T> list = query.getResultList();
		if (list.size() > 1) {
			log.error("There are " + list.size()
					+ " results of type "
					+ list.get(0).getClass().getSimpleName());
		} else if (list.size() == 1) {
			return list.get(0);
		}
		return null;
	}
	
	@SuppressWarnings("unchecked")
	public static <T> List<T> getCheckedResultList(Query query) {
		return query.getResultList();
	}
	
	public static Integer getCount(Query query) {
		return (Integer) query.getSingleResult();
	}
	
	public static Key getKey(String key){
		if(key==null){
			return null;
		}
		else{
			return KeyFactory.stringToKey(key);
		}
	}

	public static String getString(Key key){
		if(key==null){
			return null;
		}
		else{
			return KeyFactory.keyToString(key);
		}
	}
}
